package com.lifesting.tool.j2as3.visitor;

import java.util.ArrayList;
import java.util.List;

public abstract class Node {
	protected Node parent;
	protected List<Node> children = new ArrayList<Node>();
	protected String qualifiedName;
	protected String javaFilePath; //null if binary
	protected int start;
	protected int length;
	public String getQualifiedName() {
		return qualifiedName;
	}

	public Node(String qualifiedName) {
		super();
		this.qualifiedName = qualifiedName;
	}
	public Node hostable(Node node) {
		for (Node n : children) {
			if (n.getQualifiedName().equals(node.getQualifiedName())) {
				return n;
			}
		}
		return null;
	}
	 
	public Node getParent() {
		return parent;
	}

	public void setParent(Node parent) {
		this.parent = parent;
	}
	public void addGroup(List<Node> group){
		children.addAll(group);
		for (Node n: group){
			assert (n.getClass() == this.getClass());
			n.setParent(this);
		}
	}
	public List<Node> getChildren() {
		return children;
	}
	public void addChild(Node node) {
		assert (node.getClass() == this.getClass());
		Node host_node;
		if ((host_node = hostable(node)) != null){
			host_node.addGroup(node.getChildren());
		}
		else{
			children.add(node);
			node.setParent(this);
		}
	}
	public void removeChild(Node n){
		if (children.remove(n)){
			n.setParent(null);
		}
	}
	public void accept(Visitor v){
		if(v.visit(this)){
			for (Node n : children){
				n.accept(v);
			}
		}
		v.endVisit(this);
	}

	public String getJavaFilePath() {
		return javaFilePath;
	}

	public void setJavaFilePath(String javaFilePath) {
		this.javaFilePath = javaFilePath;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}
	
}
